package com.fla.puzzle.ui;

import java.util.Collections;
import java.util.List;

import com.danikula.aibolit.Aibolit;
import com.danikula.aibolit.annotation.InjectView;
import com.fla.puzzle.GameModelManager;
import com.fla.puzzle.PackManager;
import com.fla.puzzle.PuzzleApplication;
import com.fla.puzzle.R;
import com.fla.puzzle.pack.Pack;
import com.fla.puzzle.ui.game.GameModel;
import com.fla.puzzle.ui.support.CustomGallery;
import com.fla.puzzle.ui.support.ReflectedDisplayer;
import com.fla.puzzle.utils.AndroidUtils;
import com.fla.puzzle.utils.Utils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;

import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Shows available in this application game packages - {@link Pack}
 */
public class PackSelectorActivity extends BaseActivity {
    private PackManager packManager = PuzzleApplication.getInstance().getPackManager();
    private GameModelManager gameModelManager = PuzzleApplication.getInstance().getGameModelManager();

    @InjectView(R.id.packGallery)
    private CustomGallery packGallery;

    private PackAdapter packAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Aibolit.setInjectedContentView(this, R.layout.pack_selector_activity);

        packAdapter = new PackAdapter();
        packGallery.setAdapter(packAdapter);
        packGallery.setOnItemClickListener(new ItemClickedHandler());

        packAdapter.setPacks(packManager.getAll());

        boolean shown = AndroidUtils.showWhatsNewIfNecessary(this, new WhatsNewCancelHandler());
        if (!shown) {
            showRestoreGameDialogIfNeeded();
        }
    }

    private class WhatsNewCancelHandler implements OnCancelListener {
        @Override
        public void onCancel(DialogInterface dialog) {
            showRestoreGameDialogIfNeeded();
        }
    }

    private void showRestoreGameDialogIfNeeded() {
        if (gameModelManager.savedGameExist()) {
            Utils.showOkNoDialog(this, getString(R.string.saved_game), getString(R.string.restore_saved),
                new RestoredGameStarter());
        }
    }

    private class PackAdapter extends BaseAdapter {
        private List<Pack> packs = Collections.EMPTY_LIST;
        private DisplayImageOptions options;

        public PackAdapter() {
            options = new DisplayImageOptions.Builder().cacheInMemory().displayer(new ReflectedDisplayer(3))
                .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2).build();
        }

        public void setPacks(List<Pack> packs) {
            this.packs = packs;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return packs.size();
        }

        @Override
        public Pack getItem(int position) {
            return packs.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = LayoutInflater.from(PackSelectorActivity.this).inflate(R.layout.pack_gallery_item, null);
            }

            Pack pack = getItem(position);

            TextView name = (TextView) view.findViewById(R.id.name);
            TextView description = (TextView) view.findViewById(R.id.description);
            ImageView image = (ImageView) view.findViewById(R.id.image);
            ImageView hdImage = (ImageView) view.findViewById(R.id.hdImage);

            name.setTypeface(PuzzleApplication.getInstance().getHeaderTypeface());
            name.setText(pack.getName());
            description.setText(pack.getDescription());

            hdImage.setVisibility(pack.isHd() ? View.VISIBLE : View.GONE);

            ImageLoader.getInstance().displayImage(Utils.toURI(pack.getPreviewImageId()).toString(), image, options);

            return view;
        }
    }

    private class ItemClickedHandler implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            PuzzleSelectorActivity.start(PackSelectorActivity.this, packAdapter.getItem(position).getId());
        }
    }

    private class RestoredGameStarter implements OnClickListener {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            GameModel gameModel = gameModelManager.restoreGame();
            gameModelManager.removeSavedGame();

            if (gameModel != null) {
                GameActivity.start(PackSelectorActivity.this, gameModel, false);
            }
            else {
                Toast.makeText(PackSelectorActivity.this, "Couldn't restore previously saved game.", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
